import React from 'react';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Input, message, Button, Card, Checkbox, Select, Tree } from 'antd';
import { connect } from 'dva';
import PropTypes from 'prop-types';
import router from 'umi/router';
import * as R from 'ramda';

const transferOption = (arrayData = [], keyValue = ['value', 'label']) =>
  R.map(
    item => <Select.Option key={item[keyValue[0]]}>{item[keyValue[1]]}</Select.Option>,
    arrayData,
  );
const CheckboxGroup = Checkbox.Group;
const FormItem = Form.Item;
const { TextArea } = Input;
const formItemLayout = {
  labelCol: {
    xs: { span: 12 },
    sm: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 4 },
    sm: { span: 14 },
  },
};
@Form.create()
@connect((state: any) => ({
  modelGroup: state.modelGroup,
  loading: state.loading.models['modelGroup'],
  menu: state.menu,
}))
export default class ModelGroupAdd extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      formValues: {},
      formData: {},
      seriesOptions: [], // 车系列表
      selectOptions: [], // 车型列表
      indeterminate: true, // 全选状态控制
      checkAll: false,
      checkedList: [], // 车系选中结果
      buttonLoading: false,

      treeKeys: [],
      checkedKeys: [],
      halfCheckedKeys: [],
      defaultCheckedKeys: [],
      treeFormKey: new Date().getTime(),
      brandOptions: [],
      brandId: '',
    };
  }

  static contextTypes = {
    permissions: PropTypes.array,
  };
  componentWillMount() {
    if (this.props.location && this.props.location.state) {
      this.setState({
        brandOptions:this.props.location.state.brandOption,
        brandId: this.props.location.state.brandId,
      });
    }
  }
  componentDidMount() {
    // 获取车系数据
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const brandId = this.props.location && this.props.location.state.brandId;
    dispatch({
      type: 'modelGroup/getDataWithRes',
      payload: { url: '/msdevice/base/vehicle/series/bybrand/list', brandId },
      callback: (e: any) => {
        if (e.data) {
          this.setState({
            seriesOptions: e.data.map(e => ({
              seriesName: e.seriesName,
              seriesCode: e.seriesCode,
            })),
          });
        }
      },
    });
  }
  //   onChange = (list: any) => {
  //     const { selectOptions } = this.state;
  //     this.setState({
  //       checkedList: list,
  //       indeterminate: !!list.length && list.length < selectOptions.length,
  //       checkAll: list.length === selectOptions.length,
  //     });
  //   };
  //   onCheckAllChange = (e: any) => {
  //     const { selectOptions } = this.state;
  //     this.setState({
  //       checkedList: e.target.checked ? selectOptions.map(item => item.value) : [],
  //       indeterminate: false,
  //       checkAll: e.target.checked,
  //     });
  //     const { form } = this.props;
  //     form.setFieldsValue({
  //       types: e.target.checked ? selectOptions.map(item => item.value) : [],
  //     });
  //   };
  // 通过车系查询车型信息
  onSerieSelect = (value: any) => {
    if (value) {
      const url = '/vehicle/group/findTypeCodeAndOptionBySeriesCode';
      this.props.dispatch({
        type: 'modelGroup/postObj',
        payload: { url, seriesCode: value },
        callback: (e: any) => {
          this.setTreeFn(e?.data);
        },
      });
    } else {
      this.setState({
        typeOptions: [],
      });
    }
  };
  handleCancel = () => {
    const { form } = this.props;
    form.resetFields();
    this.setState({
      checkedList: [],
      indeterminate: true, // 全选状态控制
      checkAll: false,
      selectOptions: [],
    });
    router.push({ pathname: '/remoteConfiguration/modelGroup' , state: {sourceRouter: 'modelGroup'} });
    // if (this.props.location && this.props.location.state) {
    //   const {pageObj , formValues, backUrl} = this.props.location.state;
    //   router.push({ pathname: backUrl, state: { pageObj: pageObj, formValues } });
    // } else {
    //   router.push({ pathname: '/remoteConfiguration/modelGroup'});
    // }
  };
  forList = (arr: any) => {
    const list = [];
    const { checkedKeys, halfCheckedKeys } = this.state;
    arr.forEach((e: any) => {
      const checkcList = [...halfCheckedKeys, ...checkedKeys];
      const bool = checkcList.includes(e.optionCode);
      let optionList = e.optionList || [];
      if (e.optionList) {
        optionList = this.forList(e.optionList);
      }
      if (bool && !e.disabled) {
        const obj = e?.typeCode
          ? {
              typeCode: e?.typeCode,
              typeName: e?.typeName,
              optionList,
            }
          : e?.optionCode.split('==')[1];
        list.push(obj);
      }
    });
    return list;
  };
  handleOk = () => {
    const {
      dispatch,
      form: { validateFields },
    } = this.props;

    validateFields((err: any, values: any) => {
      const { selectOptions } = this.state;
      const { form } = this.props;
      const optionList = this.forList(selectOptions);
      if (optionList.length === 0) {
        form.setFields({
          types: {
            value: values.types,
            errors: [new Error('请选择车型')],
          },
        });
        return;
      }

      if (err) {
        return;
      }
      this.setState({ buttonLoading: true });

      const params = { ...values, types: optionList, };
      // let params = {};
      // // params.types = this.state.checkedList;
      // params.types = values.types;
      // params.seriesCode = values.seriesCode;
      // params.remark = values.remark? values.remark : '';
      // params.name = values.name;
      dispatch({
        type: 'modelGroup/postObjWithRes',
        payload: { url: '/device/vehicle/group/save', ...params },
        callback: (response: any) => {
          if (response.statusCode === '0') {
            message.success('操作成功！');
            this.props.form.resetFields();
            this.setState({
              buttonLoading: false,
            });
            this.handleCancel();
          } else {
            this.setState({
              buttonLoading: false,
            });
          }
        },
      });
    });
  };
  setTreeFn = (data = []) => {
    const selectOptions = [];
    for (const key in data) {
      if (Object.prototype.hasOwnProperty.call(data, key)) {
        const element = data[key];
        const arr = element?.optionList || [];
        let num = 0;
        const optionList = arr.map(e => {
          const disabled = e?.isUsed;
          if (disabled) {
            num += 1;
          }
          return {
            ...e,
            disabled,
            optionCode: `${element?.typeCode}==${e.optionCode}`,
          };
        });
        selectOptions.push({
          ...element,
          optionName: element?.typeName,
          optionCode: element?.typeCode,
          optionList,
          disabled: num === optionList.length && num,
        });
      }
    }

    this.setState({
      treeFormKey: new Date().getTime(),
      selectOptions,
    });
  };
  render() {
    const {
      seriesOptions,
      selectOptions,
      indeterminate,
      checkedList,
      checkAll,
      buttonLoading,
      defaultCheckedKeys = [],
      treeFormKey,
    } = this.state;
    const {
      form: { getFieldDecorator },
    } = this.props;

    // 树形结构
    const treeConfig = {
      defaultExpandAll: true,
      defaultCheckedKeys,
      fieldNames: {
        title: 'optionName',
        key: 'optionCode',
        children: 'optionList',
      },
      titleRender(nodeData: any) {
        const { saleStyleName = '', optionName = '',optionCode='' ,typeCode=''} = nodeData;
        const id = typeCode || optionCode===0?optionCode:optionCode.split("==")[1]
        return (
          <div>
            {saleStyleName?'':id===0?'':`${id}-`}{optionName}{saleStyleName ? `-${saleStyleName}`:""}
          </div>
        );
      },
      treeData: [
        {
          optionName: '全选按钮',
          optionCode: 0,
          optionList: selectOptions,
        },
      ],
      onCheck: (arr, list) => {
        // 设置选中值
        // 设置已选择值
        const { halfCheckedKeys } = list;
        this.setState({
          checkedKeys: arr,
          halfCheckedKeys,
        });
      },
    };
    const treeForm = {
      ...formItemLayout,
      // key: treeFormKey,
      label: <span>车型&nbsp;</span>,
      initialValue: '1111',
      rules: [
        {
          required: true,
        },
      ],
    };
    return (
      <div>
        <Card bordered={false}>
          <Form layout="horizontal">
          <FormItem {...formItemLayout} label={<span>品牌&nbsp;</span>}>
              {getFieldDecorator('brandId', {
                 initialValue:this.state.brandId,
                 rules: [{ required: false, message: '请选择品牌' }],
              })(
                <Select placeholder="请选择" disabled={true}>
                  {transferOption(this.state.brandOptions, ['brandCode', 'brandName'])}
                </Select>,
              )}
            </FormItem>
            <FormItem {...formItemLayout} label={<span>车型组名称&nbsp;</span>}>
              {getFieldDecorator('name', {
                rules: [{ required: true, message: '请输入车型组名称！' }],
              })(<Input />)}
            </FormItem>
            <FormItem {...formItemLayout} label={<span>车系&nbsp;</span>}>
              {getFieldDecorator('seriesCode', {
                rules: [{ required: true, message: '请选择车系' }],
              })(
                <Select placeholder="请选择" onChange={this.onSerieSelect}>
                  {transferOption(seriesOptions, ['seriesCode', 'seriesName'])}
                </Select>,
              )}
            </FormItem>
            <FormItem {...formItemLayout} label={treeForm.label}>
              {getFieldDecorator('types', {
                ...treeForm,
              })(<Tree checkable {...treeConfig} style={{ paddingTop: '8px' }} />)}
            </FormItem>
            <FormItem {...formItemLayout} label={<span>备注&nbsp;</span>}>
              {getFieldDecorator('remark', {
                rules: [{ required: false, message: '请输入' }],
              })(<TextArea placeholder="请输入" rows={4} />)}
            </FormItem>
            <FormItem wrapperCol={{ offset: 8, span: 16 }}>
              <Button
                type="primary"
                htmlType="submit"
                loading={buttonLoading}
                onClick={this.handleOk}
              >
                {' '}
                保存{' '}
              </Button>
              <Button style={{ marginLeft: 10 }} onClick={this.handleCancel}>
                {' '}
                取消{' '}
              </Button>
            </FormItem>
          </Form>
        </Card>
      </div>
    );
  }
}
